package com.yazi.mxz.common.service.impl;

import javax.annotation.Resource;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyNoPermissionException;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.db.dao.CompanyDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Company;
import com.yazi.mxz.common.service.CompanyService;

@Service("companyService")
public class CompanyServiceImpl extends BasicService<Company> implements CompanyService {
	private static Logger log = LoggerFactory.getLogger(CompanyServiceImpl.class);

	@Resource
	CompanyDao companyDao;

	@Override
	protected Dao<Company> getDao() {
		return companyDao;
	}
	
	@Override
	public Company edit(Company from, Company to) {
		log.debug("modify：companyId={}", to.getCompanyId());
		
		// 防止篡改以下信息
		from.setAddTime(null);
		from.setCompanyId(null);
		from.setCodeRemain(null);
		from.setCodeSeq(null);
		from.setStoreRemain(null);
		from.setCatRemain(null);
		from.setMemRemain(null);
		ValueFactory.combine(from, to);
		
		return companyDao.merge(to);
	}

	@Override
	public String editCodeSeq(long companyId) throws MyException {
		log.debug("modifyCodeSeq：companyId={}", companyId);
		
		Company company = companyDao.get(companyId);
		if (company.getCodeRemain() <= 0) {
			throw new MyNoPermissionException("内码数量已达上限");
		}
		int seq = company.getCodeSeq() + 1;
		company.setCodeRemain(company.getCodeRemain() - 1);
		company.setCodeSeq(seq); 
		companyDao.merge(company);

		return MyUtil.makeBarCode(seq);
	}

}
